<?php


namespace app\controller\admin;


use app\model\goods\GoodsModel;
use app\model\team\TeamModel;
use app\model\user\UserAuthModel;
use app\model\user\UserModel;
use app\service\team\TeamRelationService;
use app\service\utils\GenerateUserNickService;
use app\validate\user\UserRegisterValidate;
use think\facade\Db;

class UserAuthController extends BaseAdminController
{

    function setModel()
    {
        return new UserAuthModel();
    }

    function setWithModel()
    {
        return ['invite'];
    }

    function setSearch()
    {
        $where = [];
        $next = $this->request->param('next', '', 'trim');
        if ($next) {
            $pid = UserModel::where('nick|mobile', '=', $next)->value('id');
            $where[] = ['pid', '=', $pid];
        }
        $isActive = $this->request->param('is_active', '', 'trim');
        if ($isActive != '') {
            $where[] = ['is_active', '=', $isActive];
        }
        $startTime = $this->request->param('start_time', '', 'trim');
        if ($startTime) {
            $where[] = ['create_time', '>=', strtotime($startTime)];
        }
        $endTime = $this->request->param('end_time', '', 'trim');
        if ($endTime) {
            $where[] = ['create_time', '<', strtotime($endTime) + 86400];
        }
        return [
            'like' => ['nick', 'mobile'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function save()
    {
        try {
            $data = $this->request->except(['create_time']);
            // 推荐人
            if (isset($data['invite_mobile']) && $data['invite_mobile']) {
                $pinfo = $this->setModel()->where('mobile', $data['invite_mobile'])->find();
                if (!$pinfo) {
                    throw new \Exception('上级不存在');
                }
                $data['pid'] = $pinfo['id'];
                $data['route_id'] = isset($data['route_id']) ? $data['route_id'] : $pinfo['route_id'];
            }
            if (!$data['id']) {
                do {
                    $code = random(6);
                    $info = $this->setModel()->where('invite_code', $code)->find();
                } while ($info);
                $data['is_active'] = 1;
                $data['invite_code'] = $code;
                $data['remark'] = isset($data['is_system']) ? $data['is_system'] : 0;
                $data['nick'] = $data['nick'] ?: GenerateUserNickService::generateUserNick();
                $this->setModel()->save($data);
            } else {
                $model = $this->setModel()->find($data['id']);
                $model->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}